﻿namespace AvaloniaApplication1;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class SocketClient
{
    private TcpClient _client;
    private NetworkStream _stream;
    
    /// <summary>
    /// Socket连接
    /// </summary>
    /// <param name="ip"></param>
    /// <param name="port"></param>
    public async Task ConnectAsync(string ip, int port)
    {
        _client = new TcpClient();
        await _client.ConnectAsync(ip, port);
        _stream = _client.GetStream();
    }

    /// <summary>
    /// 发送数据
    /// </summary>
    /// <param name="data"></param>
    public async Task SendDataAsync(string data)
    {
        if (_stream.CanWrite)
        {
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            await _stream.WriteAsync(buffer, 0, buffer.Length);
        }
    }
    
    /// <summary>
    ///  接收数据
    /// </summary>
    /// <returns></returns>
    public async Task<string> ReceiveDataAsync()
    {
        if (_stream.CanRead)
        {
            byte[] buffer = new byte[_client.ReceiveBufferSize];
            int bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length);
            return Encoding.ASCII.GetString(buffer, 0, bytesRead);
        }

        return null;
    }
   
    /// <summary>
    /// 释放连接
    /// </summary>
    public void Disconnect()
    {
        _stream.Close();
        _client.Close();
    }
}
